package com.sciology.xpathutility.utils;

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Attr;

import javax.xml.namespace.NamespaceContext;
import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;

public class NamespaceContextImpl implements NamespaceContext {
    private Map nsMap = new HashMap();

    public NamespaceContextImpl() {
    }

    public NamespaceContextImpl(Element el) {
        this.nsMap = getNSMap(el);
    }

    public NamespaceContextImpl(Map nsMap) {
        this.nsMap = nsMap;
    }

    public void addNamespace(String prefix, String uri) {
        nsMap.put(prefix, uri);
    }
    
    public void addNamespaceMap(Map map) {
        nsMap.putAll(map);
    }

    public Map getNamespaceMap() {
        return nsMap;
    }
    
    public String getNamespaceURI(String prefix) {
        return (String)nsMap.get(prefix);
    }

    public String getPrefix(String namespaceURI) {
        Iterator itr = nsMap.entrySet().iterator();
        while ( itr.hasNext() ) {
            Map.Entry e = (Map.Entry)itr.next();
            String uri = (String)e.getValue();
            if (uri.equalsIgnoreCase(namespaceURI) )
                return (String)e.getKey();
        }
        return null;
    }

    public Iterator getPrefixes(String namespaceURI) {
        return nsMap.keySet().iterator();
    }

    private Map getNSMap(Element el) {
        Map map = new HashMap();
        NamedNodeMap nnm = el.getAttributes();
        int len = nnm.getLength();
        for (int i=0; i < len; ++i) {
            Attr a = (Attr) nnm.item(i);
            String attrName = a.getName();
            if (attrName.startsWith("xmlns:")) {
                int idx = attrName.indexOf(':');
                String prefix = attrName.substring(idx+1);
                map.put(prefix, a.getValue());
            }
        }
        return map;
    }

}
